import re
from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'token': token,
        'username': user.username,
        'user_id': user.id
    }


# 默认是 {'token': token}


class UsernameMobileAuthBackend(ModelBackend):
    """
      自定义用户名或手机号认证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):

        # 1、判断username传递的数据是否是一个手机号
        try:
            if re.match(r'^1[3-9]\d{9}$', username):
                # 2、如果是手机号，按照手机查询用户对象
                user = User.objects.get(mobile=username)
            else:
                user = User.objects.get(username=username)
        except:
            user = None
        # 判断密码
        if user is not None and user.check_password(password):
            # 3、返回查询后的数据对象
            return user
